package com.ys.nms.module.business.controller.admin.redData;


import com.jcraft.jsch.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "ssh.config")
public class SshConfig {
    private String host;
    private int port = 22;
    private String username;
    private String password;
    private String privateKeyPath;

    public Session createSession() throws JSchException {
        JSch jsch = new JSch();

        // 优先使用私钥认证
        if (privateKeyPath != null && !privateKeyPath.trim().isEmpty()) {
            jsch.addIdentity(privateKeyPath);
        }

        Session session = jsch.getSession(username, host, port);

        // 如果配置了密码，使用密码认证
        if (password != null && !password.trim().isEmpty()) {
            session.setPassword(password);
        }

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 跳过主机密钥检查
        session.setConfig(config);

        return session;
    }

    public boolean testConnection() {
        Session session = null;
        try {
            session = createSession();
            session.connect(5000); // 5秒超时
            return true;
        } catch (Exception e) {
            log.error("SSH连接测试失败: {}", e.getMessage());
            return false;
        } finally {
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}